package day10.gec.threadlocal4;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

class PrintDemo extends RecursiveAction {

    // 定义的常量 自定义
    public static final int FIFTY = 50;
    // 开始
    private int start;
    // 结束
    private int end;

    public PrintDemo(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        // 判断
        if (end - start <= FIFTY) {
            for (int i = start; i < end; i++) {
                System.out.println(Thread.currentThread().getName() + "i的值:" + i);
            }
        }else {
            // 进行找出middle
            int middle = (end + start) / 2;
            // 分解任务
            PrintDemo left = new PrintDemo(start, middle);
            PrintDemo right = new PrintDemo(middle, end);
            // 任务
            left.fork();
            right.fork();
        }
    }
}

/**
 * 假设一堆打印任务50个打印一台及其,如果超过50个打印，分若干个子打印任务
 */

public class ForkJoinPoolDemo2 {
    public static void main(String[] args) throws InterruptedException {
        // 创建ForkJoinPool线程池
        ForkJoinPool fjp = new ForkJoinPool(32767);
        // 提交任务
        fjp.submit(new PrintDemo(0, 300));

        // 定时两秒完成任务
        fjp.awaitTermination(2, TimeUnit.SECONDS);
    }
}
